import { toValue } from "vue"
import { h, render } from 'vue';
import { ElScrollbar } from 'element-plus'
import { throttle } from "lodash-unified"
const useElScrollbar = (element, options = {}) => {
    const { timeout = 0, addTouch = false } = options
    if (element instanceof HTMLElement) {
        const { moveToElScrollbar = false, addUntouchClass = false } = options

        let ele = toValue(element)
        if (moveToElScrollbar) {
            const parentNode = ele.parentNode
            const vnode = h(ElScrollbar, null)
            render(vnode, parentNode)
            parentNode.querySelector(".el-scrollbar__view").append(ele)
            ele = parentNode
        }
        if (addUntouchClass) ele.classList.add("untouchable")

        const wrap = ele.querySelector(".el-scrollbar__wrap")
        let offsetX = 0
        const touchstart = (e) => {
            e.preventDefault()
            offsetX = e.touches[0].pageX
        }

        const touchmove = throttle((e) => {
            e.preventDefault()
            const moveX = e.touches[0].pageX - offsetX
            offsetX = e.touches[0].pageX
            wrap.scrollLeft = wrap.scrollLeft + -1 * moveX
        })

        if (addTouch) {
            wrap.ontouchstart = touchstart
            wrap.ontouchmove = touchmove
        }
    } else {
        setTimeout(() => {
            for (let el of document.querySelectorAll(element)) {
                useElScrollbar(el, options)
            }
        }, timeout);
    }
}

export default useElScrollbar